package client.view;


import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

import javax.imageio.ImageIO;

import client.utility.Id;



public abstract class ImageDatabase {
	
	public static HashMap<Integer, int[]> mapImages, mapSizes;
	
	public static void main(String[] args) {
		ImageDatabase.getMap(new Id(10));
	}
	
	static{
		/*mapImages=new HashMap<Integer, int[]>();
		mapSizes=new HashMap<Integer, int[]>();
		
		try{
			loadImageFromFile(new File("bg1.jpg"),10);
			loadImageFromFile(new File("map1.png"),11);
			
			FileOutputStream fos = new FileOutputStream("maps");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(mapImages);
			oos.writeObject(mapSizes);
			oos.close();
		}catch(Exception ex){ex.printStackTrace();}*/
		
		try{
			FileInputStream fis = new FileInputStream("maps");
			ObjectInputStream iis = new ObjectInputStream(fis);
			mapImages = (HashMap<Integer, int[]>)iis.readObject();
			mapSizes = (HashMap<Integer, int[]>)iis.readObject();
			iis.close();
		}catch(Exception ex){System.err.println(ex);}
		
	}
	
	private static void loadImageFromFile(File file, int id) throws IOException, InterruptedException{
		BufferedImage loadImg = ImageIO.read(file);
		int width=loadImg.getWidth(), height=loadImg.getHeight();
		
		mapImages.put(id,getArrayFromImage(loadImg,width, height));  
		mapSizes.put(id, new int[]{width,height});
	}
	
	private static int[] getArrayFromImage(Image img, int width, int height) throws InterruptedException {
		int[] pixels = new int[width * height];
		PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, pixels,0, width);
		pg.grabPixels();
		return pixels;
	}
	 
	private static Image getImageFromArray(int[] pixels, int width, int height) {
		MemoryImageSource mis = new MemoryImageSource(width, height, pixels,0, width);
		Toolkit tk = Toolkit.getDefaultToolkit();
		return tk.createImage(mis);
	}
	
	public static Image getMap(Id id){
		int[] sizes=mapSizes.get(id.hashCode());
		return getImageFromArray(mapImages.get(id.hashCode()), sizes[0], sizes[1]);
	}

}
